package cn.tedu._04mvcboot03.controller;

import cn.tedu._04mvcboot03.common.response.JsonResult;
import cn.tedu._04mvcboot03.common.response.StatusCode;
import cn.tedu._04mvcboot03.mapper.UserMapper;
import cn.tedu._04mvcboot03.pojo.dto.UserArticleDTO;
import cn.tedu._04mvcboot03.pojo.dto.UserLoginDTO;
import cn.tedu._04mvcboot03.pojo.entity.Article;
import cn.tedu._04mvcboot03.pojo.vo.ArticleVO;
import cn.tedu._04mvcboot03.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Validated
@Slf4j
@Api(tags = "用户模块")
@RestController
@RequestMapping("v1/users/")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        /*
            1.获取用户名和密码;
            2.校验用户名和密码[接口方法]
              SELECT id,password,nickname FROM mvcbd.mvc_user
              WHERE username=? AND password=?
            3.判断UserVO是否为null
              3.1 为null: 用户名或密码错误;
              3.2 不为null: session处理; 登录成功
         */
        log.debug("userLoginDTO = " + userLoginDTO);
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        //调用接口方法
        UserVO userVO = userMapper.select(username, password);
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userVO);
        return JsonResult.ok();
    }

    @ApiOperation(value = "发布文章")
    @PostMapping("article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("userArticleDTO = " + userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        if (userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        //插入数据
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO, article);
        article.setUserId(userVO.getId());
        //调用接口
        userMapper.insertArticle(article);

        return JsonResult.ok();
    }

    @ApiOperation(value = "查看文章")
    @GetMapping("selectByArticleId")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章ID在1-100之间") @RequestParam int id){
        ArticleVO articleVO = userMapper.selectByArticleId(id);

        return JsonResult.ok(articleVO);
    }
}








